package com.qf.mp2302.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.mp2302.entity.User;
import com.qf.mp2302.mapper.UserMapper;
import com.qf.mp2302.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    UserMapper userMapper;


    @Override
    public List<User> findUsers(User user) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();

        wrapper.eq(StringUtils.isNotBlank(user.getName()),"name",user.getName())
                .eq(StringUtils.isNotBlank(user.getEmail()),"t_email",user.getEmail())
                .eq(user.getAge()!=null,"age",user.getAge())
                ;

        List<User> users = userMapper.selectList(wrapper);

        return users;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public User regist(User user) throws SQLException {
        // 保存用户
        userMapper.insert(user);

        // 其他代码
//        int a = 1/0;

        // 抛出 SQLException
        if (true){
            throw new SQLException("sql error");
        }

        return user;
    }

    @Override
    public User transInvalid(User user) throws SQLException {

        // 如果通过this，调用添加了@Transactional注解的方法，
        // this指向的是该Servcie的原来的对象，而不是带有事务逻辑的动态代理对象，
        // 因此会导致事务失效
        return this.regist(user);
    }
}
